package com.flc.gateway.session;

import com.flc.gateway.model.CommandHelper;
import io.netty.channel.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * Session的集中管理
 * 包含了所有设备与session关系的缓存map
 * 这两个map实时更新，线程安全
 * @author haizi
 * @date 2018/1/1
 */
public class SessionManager {

    private static final Logger logger = LoggerFactory.getLogger(SessionManager.class);

    /** 缓存设备id与对应的会话 */
    private static ConcurrentMap<Long, Session> sessionMap = new ConcurrentHashMap<>();
    /** 缓存设备id与对应的通道ID */
    private static ConcurrentMap<String, Long> sessionIdMap = new ConcurrentHashMap<>();

    /**
     * 往设备端发送数据
     * @param command 待发送的数据
     * @return 是否写成功
     */
    public static boolean sendCmdToDevice(CommandHelper command) {
        if (sessionMap.get(command.getDeviceId()) != null) {
            sessionMap.get(command.getDeviceId()).write(command.getCommand());
            return true;
        } else {
            return false;
        }
    }

    /**
     * 根据设备ID获取当前Session 理论上这接口用不着
     * @param deviceId 设备ID
     * @return 对应的Session对象
     */
    public static Session getSessionById(Long deviceId) {
        return sessionMap.get(deviceId);
    }

    /**
     * 注册session
     * @param deviceId 设备ID
     * @param channel 通道对象
     */
    public static void registerSession(Long deviceId, Channel channel) {
        Session session = new Session(channel);
        sessionMap.put(deviceId, session);
        sessionIdMap.put(channel.id().asLongText(), deviceId);

        System.out.println("设备ID: " + deviceId + "  通道ID：" + channel.id().asLongText());
    }

    /**
     * 注销session
     * @param channel 已经断开的通道
     */
    public static void releaseSession(Channel channel) {
        System.out.println("sessionIdMapSize: " + sessionIdMap.size());
        System.out.println("sessionMapSize: " + sessionMap.size());

        if(channel  == null){
            return;
        }
        Long deviceId = null;
        Session session = null;
        if (sessionIdMap.containsKey(channel.id().asLongText())) {
            deviceId = sessionIdMap.remove(channel.id().asLongText());
        }
        if (deviceId !=null && sessionMap.containsKey(deviceId)) {
            session = sessionMap.remove(deviceId);
            session.close();
        }
        System.out.println("sessionIdMapSize: " + sessionIdMap.size());
        System.out.println("sessionMapSize: " + sessionMap.size());

        logger.info("移除Session成功，关闭通道成功！");
    }
}
